const MAX_NUM = 140;
const MAX_IMAGE_NUM = 9;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wordsNum:0,
    footerBottom:0,
    imageLists:[],
    showAdd:true
  },
  onInput(e) {
    let wordsNum = e.detail.value.length
    if (wordsNum <= MAX_NUM) {
      this.setData({
        wordsNum
      })
      this.data.content = e.detail.value.trim()
    }
  },
  onFocus(e) {
    this.setData({
      footerBottom:e.detail.height + 48
    })
  },
  onBlur() {
    this.setData({
      footerBottom:0
    })
  },
  //选择添加图片
  onSelect() {
    let max = MAX_IMAGE_NUM - this.data.imageLists.length
    wx.chooseImage({
      count: max,
      sizeType:['original', 'compressed'],
      sourceType:['album', 'camera'],
      success:(res) => {
        this.setData({
          imageLists:this.data.imageLists.concat(res.tempFilePaths)
        })
        max = MAX_IMAGE_NUM - this.data.imageLists.length
        if (max <= 0) {
          this.setData({
            showAdd:false
          })
        }
      }
    })
  },
  //删除图片
  deleteImage(ev) {
    let index = ev.target.dataset.index
    this.data.imageLists.splice(index,1)
    this.setData({
      imageLists:this.data.imageLists
    })
    let max = MAX_IMAGE_NUM - this.data.imageLists.length
    if (max > 0) {
      this.setData({
        showAdd:true
      })
    }
  },
  //预览图片
  handlePreviewImage(ev) {
    let url = ev.target.dataset.url
    wx.previewImage({
      urls: this.data.imageLists,
      current:url
    })
  },
  //发布
  handlePubClick() {
    this.uploadFile()
  },
  //上传文件
  uploadFile() {
    let images = this.data.imageLists
    let promiseArrs = []
    for(let i =0;i< images.length;i++) {
      let item = images[i]
      let ramdom = String(Math.random()).slice(3)
      let suffix = /\.(\w+$)/.exec(item)[0]
      let p = new Promise((resolve,reject) => {
        wx.cloud.uploadFile({
          cloudPath:`blog/${Date.now()}-${ramdom}${suffix}`,
          filePath:item,
          success:(res) => {
            resolve(res.fileID)
          },
          fail:(err) => {
            reject(err)
          }
        })
      })
      promiseArrs.push(p)     
    }
    wx.showLoading({
      title:'发布中'
    })
    Promise.all(promiseArrs).then(fileIds => {
      this.saveBlogToDb(fileIds)
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: '上传文件失败',
        icon:'error'
      })
    })
  },
  //保存入库
  async saveBlogToDb(fileIds) {
    try {
      let { avatarUrl,nickName,content } = this.data
      if (!content) {
        return wx.showToast({
          title: '请输入要发布的内容',
          icon:'none'
        })
      }
      wx.showLoading({
        title: '发布中',
        mask:true
      })
      let res = await wx.cloud.callFunction({
        name:'blog',
        data:{
          $url:'save',
          fileIds,
          content,
          avatarUrl,
          nickName
        }
      })
      if (res.errMsg.indexOf('ok') > -1) {
        wx.showToast({
          title: '发布成功',
        })
       wx.navigateBack()
       let pages = getCurrentPages();
       let prevPage = pages[pages.length - 2]
       prevPage.onPullDownRefresh()
      } else {
        wx.showToast({
          title: '出错了,过一会再试',
        })
      }
    } catch(err) {
      console.log('xxx:',err)
      wx.showLoading()
      wx.showToast({
        title: '发布失败',
        icon:'error'
      })
    } finally {
      wx.showLoading()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.avatarUrl = options.avatarUrl
    this.data.nickName = options.nickName
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})